package com.atguigu.chapter07.D04_State;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Author: Pepsi
 * Date: 2023/8/9
 * Desc:
 */
public class Flink08_State_Key_Aggregate_Tuple2 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        env
                .socketTextStream("hadoop101", 9999) // socket只能是1
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                .keyBy(WaterSensor::getId)
                // 键控状态必须在keyBy后使用
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private AggregatingState<WaterSensor, Double> avgVcState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        avgVcState = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<WaterSensor, Tuple2<Integer, Long>, Double>(
                                "avgVcState",
                                new AggregateFunction<WaterSensor, Tuple2<Integer, Long>, Double>() {
                                    @Override
                                    public Tuple2<Integer, Long> createAccumulator() {
                                        return new Tuple2<Integer, Long>(0,0L);
                                    }

                                    @Override
                                    public Tuple2<Integer, Long> add(WaterSensor value, Tuple2<Integer, Long> acc) {
                                        acc.f0 += value.getVc();
                                        acc.f1++;
                                        return acc;
                                    }

                                    @Override
                                    public Double getResult(Tuple2<Integer, Long> acc) {
                                        return acc.f0 * 1.0 / acc.f1;
                                    }

                                    @Override
                                    public Tuple2<Integer, Long> merge(Tuple2<Integer, Long> a, Tuple2<Integer, Long> b) {
                                        return null;
                                    }
                                },
//                                TypeInformation.of(new TypeHint<Tuple2<Integer, Long>>() {})
                                // 类型还可以这样声明，简单
                                Types.TUPLE(Types.INT,Types.LONG)
                        ));
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        avgVcState.add(value);
                        out.collect(ctx.getCurrentKey()+" 的平均水位："+avgVcState.get());
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}